<?php
//定时取消未支付订单
namespace app\api\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
use think\Log;


class OrderCancle extends Command
{
    protected function configure()
    {
        $this->setName('order_cancle');
    }

    protected function execute(Input $input, Output $output)
    {
        $noPayOrder = db('order')->where(['order_status'=>0])->where('order_type','in',[1,2])->select();
        try{
            foreach ($noPayOrder AS $key => $value) {
                $orderId = $value['id'];
                $orderInfo = $value;
                $cha = time()-$value['addtime'];
                if ($cha >= 1800) {
                    db('order')->where('id',$orderId)->update([
                        'order_status' => 5,
                        'cancle_type' => 1,
                        'qx_time' => time()
                    ]);
                    //加库存
                    $orderGoods = db('order_goods')->where('order_id',$orderId)->select();
                    foreach ($orderGoods AS $key => $value) {
                        $storeGoodsId = db('store_goods')->where(['store_id'=>$orderInfo['store_id'],'goods_id'=>$value['goods_id']])->value('id');
                        db('store_goods')->where('id',$storeGoodsId)->lock(true)->find();
        
                        db('store_goods')->where('id',$storeGoodsId)->inc('stock',$value['num'])->inc('real_stock',$value['num'])->update();
                    }

                    //还原采购单
                    db('order_goods_store')->where('order_id',$orderId)->update([
                        'order_id'=>0,
                        'order_goods_id'=>0,
                        'p_user_id'=>0,
                        'p_user_idtwo'=>0,
                        'fx_price'=>0,
                        'fx_pricetwo'=>0,
                        'order_price'=>0,
                        'lirun'=>0,
                    ]);
                    //订单是否可退
                    if ($orderInfo['is_ketui'] == 0) {
                        db('order')->where('id',$orderId)->update([
                            'is_ketui'=>1
                        ]);
                    }
                }
            }
        } catch (ValidateException|PDOException|Exception $e) {
            $this->error($e->getMessage());
        }
        exit('取消订单脚本执行完成');
    }
}
